﻿using System;
using System.Collections.Generic;
using System.Linq;
using AvalonDock;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.Quik;
using RiskMan.Config;

namespace RiskMan.Views.Stop
{
    public partial class StopView : DocumentContent
    {
        static object locker = new object();


        public void LogicMethod ( Object sender, EventArgs args )
        {
            bool running = false;

            if ( mainWindow.Terminals == null )
                running = false;
            else
            {
                if ( mainWindow.Terminals.CountConnected( ) > 0 )
                    running = true;
                else
                    running = false;
            }

            button3.IsEnabled = running;
            button4.IsEnabled = running;

            if (running == true)
            {
                //lock (locker)
                //{

                    List<PositionModel> position = GetCount(mainWindow._dataProvider.EmitentLimiteList);
                    position.AddRange(GetCount(mainWindow._dataProvider.FortsPositionsList));

                    for (int i = 0; i < position.Count; i++)
                    {
                        _formate = cfg.SetFormate(mainWindow._dataProvider.GetAccuraccy(position[i].Seccode));
                        this.Clear(mainWindow._dataProvider.StopLossOrderList);

                        WorkingTimeClass time = new WorkingTimeClass(position[i].Account);
                        if (time.IsWork() == true)
                        {

                            if (IsRun(position[i]) == true)
                            {
                                // время работы
                                if (position[i].Count != 0)
                                    new StopsClass(position[i], mainWindow, _formate).Start();
                                else
                                    new StopsClass(position[i], mainWindow).Remove();
                            }
                        }
                    }


                //}
            }
        }

        private void Clear(List<StopOrderModel> list)
        {
            mainWindow._dataProvider.StopLossOrderList = list.Where(a => a.Status != cfg.Cancel).ToList();
        }

        
        private List<DealModel> GetList(DealModel deal, List<DealModel> list)
        {
            bool res = false;

            for (int i = 0; i < list.Count; i++)
                if (list[i].Seccode == deal.Seccode)
                {
                    res = true;
                    list[i] = deal;
                }

            if (res == false)
                list.Add(deal);

            return list;
        }
    }
}
